<?php

class UserProfilesController extends Controller
{
	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}	

	/**
	 * Displays a particular model.
	 */
	public function actionIndex(){
		ob_start();
		$model = UserProfiles::model()->find("user_id=".Yii::app()->user->id);
		if ($model == null) {
			$model=new UserProfiles;	
		}
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
	   	// $transaction = Yii::app()->db->beginTransaction();
		if(isset($_POST['UserProfiles'])) {
			try {
				$model->attributes=$_POST['UserProfiles'];
				$model->avatar = CUploadedFile::getInstance($model, 'avatar');
				if($model->save()) {
					if (isset($_POST["UserProfiles"]["avatar"])){
						$path = Yii::getPathOfAlias('webroot').'/data/avatars/';
	                	$model->avatar->saveAs($path.$model->avatar);
					}
					$this->redirect(array('view','id'=>$model->id));
				}
				// $transaction->commit();
			}catch(Exception $e) {
				// $transaction->rollBack();
			}
		}
		$this->render('index',array(
			'model'=>$model,
		));
		ob_flush();
	}
    public function actionView($id){
    	$this->layout = "//layouts/userpage";
        $model=UserProfiles::model()->findByPk($id);
        if ($model != null) {
        	$this->render('view',array(
				'model'=>$model,
			));	
        }else{
        	$da ="Bạn vào không đúng";
 			$this->render('application.views.site.error',array('data'=>$da));
        }
    }
}
